<template>
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="20" :xs="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="73px">
            <el-form-item label="科研基地名称查询" prop="baseNameSearch">
              <el-input v-model="queryParams.baseNameSearch" placeholder="请输入科研基地名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="重点学科名称查询" prop="disciplineNameSearch">
              <el-input v-model="queryParams.disciplineNameSearch" placeholder="请输入重点学科名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="科研创新团队名称查询" prop="teamNameSearch">
              <el-input v-model="queryParams.teamNameSearch" placeholder="请输入科研创新团队名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item> -->
  
            <el-form-item>
              <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
  
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd"
                v-hasPermi="['user:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="EditPen" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['user:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" size="mini" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['user:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                    <el-button
                       type="info"
                       plain
                       icon="Upload"
                       @click="handleImport"
                       v-hasPermi="['user:import']"
                    >导入</el-button>
                 </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="platformId" label="ID" width="90" />
      <el-table-column prop="userId" label="用户ID" width="90" />
      <el-table-column prop="baseName" label="科研基地名称" width="120" />
      <el-table-column prop="baseCategory" label="科研基地类别" width="120" />
      <el-table-column prop="baseScore" label="科研基地分值" width="120" />
      <el-table-column prop="disciplineName" label="重点学科名称" width="120" />
      <el-table-column prop="disciplineCategory" label="重点学科类别" width="120" />
      <el-table-column prop="disciplineScore" label="重点学科分值" width="120" />
      <el-table-column prop="teamName" label="科技创新团队名称" width="120" />
      <el-table-column prop="teamCategory" label="科技创新团队类别" width="120" />
      <el-table-column prop="teamScore" label="科技创新团队分值" width="120" />
      <el-table-column prop="platformNotes" label="备注" />
    </el-table>

    <!-- 新增用户的对话框 -->
<el-dialog :title="dialogTitle" v-model="dialogVisible" width="38%">    
    <el-form ref="userForm" :model="formData" label-width="100px">

    <!-- 科研基地名称 -->
    <el-row>
      <el-col :span="25">
        <el-form-item label="科研基地名称" prop="baseName" required>
          <el-input v-model="formData.baseName" placeholder="科研基地名称"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 科研基地类别和科研基地分值 -->
    <el-row :gutter="20"> 
      <el-col :span="12">
        <el-form-item label="科研基地类别" prop="baseCategory" required>
          <el-input v-model="formData.baseCategory" placeholder="科研基地类别"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="科研基地分值" prop="baseScore" required>
          <el-input v-model="formData.baseScore" placeholder="请输入科研基地分值"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 重点学科名称 -->
    <el-row>
      <el-col :span="25">
        <el-form-item label="重点学科名称" prop="disciplineName" required>
          <el-input v-model="formData.disciplineName" placeholder="请输入重点学科名称"></el-input>
        </el-form-item>
      </el-col>
    </el-row>


    <!-- 重点学科类别和重点学科分值 -->
    <el-row :gutter="20"> 
      <el-col :span="12">
        <el-form-item label="重点学科类别" prop="disciplineCategory" required>
          <el-input v-model="formData.disciplineCategory" placeholder="重点学科类别"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="重点学科分值" prop="disciplineScore" required>
          <el-input v-model="formData.disciplineScore" placeholder="请输入重点学科分值"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 科技创新团队名称 -->
    <el-row>
      <el-col :span="25">
        <el-form-item label="科技创新团队名称" prop="teamName" required>
          <el-input v-model="formData.teamName" placeholder="请输入科技创新团队名称"></el-input>
        </el-form-item>
      </el-col>
    </el-row>


    <!-- 科技创新团队类别和科技创新团队分值 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="科技创新团队类别" prop="teamCategory" required>
          <el-input v-model="formData.teamCategory" placeholder="请输入科技创新团队类别"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="科技创新团队分值" prop="teamScore" required>
          <el-input v-model="formData.teamScore" placeholder="请输入科技创新团队分值"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 备注 -->
    <el-row>
      <el-col :span="25">
        <el-form-item label="备注" prop="platformNotes" required>
          <el-input v-model="formData.platformNotes" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </template>
</el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
<!-- 分页组件 -->
<Pagination v-model="queryParams" :total="total" @change="handleChange" />
    <el-footer>

    </el-footer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { listUser, delUser, addUser, updateUser } from "@/api/user";
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from '@/components/Pagination/index.vue';

const tableData = ref([]); // 初始化为响应式数组
const title = ref("");
const open = ref(false);
//处理选中行
const selectedRow = ref(null);

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 上传的地址
  url: "http://localhost:8080/user/importData",
  // headers: {
  //   withCredentials: true
  // },
  // url: import.meta.env.VITE_APP_BASE_API + "/user/importData"
});

// 对话框相关变量
const dialogVisible = ref(false);
const dialogTitle = ref('新增用户');
const formData = reactive({
  platformId: '',
  userId: '',
  baseName: '',
  baseCategory: '',
  baseScore: '',
  disciplineName: '',
  disciplineCategory: '',
  disciplineScore: '',
  teamName: '',
  teamCategory: '',
  teamScore: '',
  platformNotes:''
});

// 定义查询参数
const queryParams = ref({
  userKeyword: '',
  currentPage: 1,
  pageSize: 10,
});
const total = ref(0);
// const queryParams = ref({
//   userKeyword: '',
// });

// 控制显示/隐藏搜索表单
const showSearch = ref(true);

// 单选和多选状态
const single = ref(false);
const multiple = ref(false);

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true; // 开始上传时禁用按钮
};

const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false; // 上传完成后启用按钮
  if (response.code === 200) {
    ElMessage.success("导入成功");
    upload.open = false; // 关闭对话框
    getUserList(); // 刷新用户列表
  } else {
    ElMessage.error(response.message || "导入失败，请检查文件格式或内容");
  }
};

// 查询方法
async function handleQuery() {
  try {
    const response = await listUser({
      ...queryParams.value,
      currentPage: queryParams.value.currentPage, // 分页从1开始
      pageSize: queryParams.value.pageSize
    });
    tableData.value = response.data.data; // 更新表格数据
    total.value = response.data.total; // 总条目数
    console.log('查询结果:', response.data);
  } catch (error) {
    console.error('查询失败:', error);
  }
}
// async function handleQuery() {
//   try {
//     const response = await listUser(queryParams.value);
//     tableData.value = response.data; // 更新表格数据
//     console.log('查询结果:', response.data);
//   } catch (error) {
//     console.error('查询失败:', error);
//   }
// }

// 重置查询条件
function resetQuery() {
  queryParams.value = {
    userKeyword: ''
  };
  handleQuery(); // 重置后重新查询
}

// 显示新增对话框
function handleAdd() {
  // 清空表单数据
  Object.assign(formData, {
  platformId: '',
  userId: '',
  baseName: '',
  baseCategory: '',
  baseScore: '',
  disciplineName: '',
  disciplineCategory: '',
  disciplineScore: '',
  teamName: '',
  teamCategory: '',
  teamScore: '',
  platformNotes:''
  });
  dialogTitle.value = '新增用户';
  dialogVisible.value = true;
}

// 提交表单到后端
async function handleSubmit() {
  try {
    let response;

    if (formData.platformId) { // 如果存在id，则为修改操作
      const sendData = {
        platformId: formData.platformId,
        userId: formData.userId,
        baseName: formData.baseNamee,
        baseCategory: formData.baseCategory,
        baseScore: formData.baseScore,
        disciplineName: formData.disciplineName,
        disciplineCategory: formData.disciplineCategory,
        disciplineScore: formData.disciplineScore,
        teamName: formData.teamName,
        teamCategory: formData.teamCategory,
        teamScore: formData.teamScore, 
        platformNotes: formData.platformNotes
      };
      response = await updateUser(sendData); // 调用API进行更新操作
      ElMessage({
        message: '修改成功',
        type: 'success'
      });
    } else { // 否则为新增操作
      const sendData = {
        userId: formData.userId,
        baseName: formData.baseNamee,
        baseCategory: formData.baseCategory,
        baseScore: formData.baseScore,
        disciplineName: formData.disciplineName,
        disciplineCategory: formData.disciplineCategory,
        disciplineScore: formData.disciplineScore,
        teamName: formData.teamName,
        teamCategory: formData.teamCategory,
        teamScore: formData.teamScore, 
        platformNotes: formData.platformNote
      };
      response = await addUser(sendData);
      ElMessage({
        message: '新增成功',
        type: 'success'
      });
    }

    dialogVisible.value = false; // 关闭对话框
    await handleQuery(); // 刷新列表以显示新添加/修改的记录
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
}

function handleSelectionChange(selection) {
  if (selection.length > 0) {
    single.value = selection.length !== 1;
    multiple.value = false; // 当有选择时，允许删除
    selectedRow.value = selection;
  } else {
    single.value = true;
    multiple.value = true; // 没有选择时，不允许删除
    selectedRow.value = null;
  }
}

//修改
async function handleUpdate() {
  if (!selectedRow.value) {
    ElMessage.error('请选择一条记录进行修改');
    return;
  }
  // 将选中的行数据赋值给formData
  if (selectedRow.value.length > 0) {
    Object.assign(formData, selectedRow.value[0]);
  }
  // 将选中的行数据赋值给formData
  // Object.assign(formData, JSON.parse(JSON.stringify(selectedRow.value)));

  dialogTitle.value = '修改用户';
  dialogVisible.value = true;
}

//删除
async function handleDelete() {
  if (!selectedRow.value || selectedRow.value.length === 0) {
    ElMessage.error('请选择一条或多条记录进行删除');
    return;
  }

  try {
    const selectedIds = selectedRow.value.map(row => Number(row.userId)); // 确保 ID 是数字

    console.log('Selected IDs:', selectedIds); // 调试信息

    await ElMessageBox.confirm(
      '是否确认删除用户编号为"' + selectedIds.join('", "') + '"的数据项？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 调用删除 API
    await delUser(selectedIds);

    // 提示删除成功
    ElMessage({
      message: '删除成功',
      type: 'success'
    });

    // 刷新列表以显示最新的更改
    await handleQuery();

    // 清除选中状态
    selectedRow.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败，请重试');
    }
  }
}


const handleChange = (newPage, newPageSize) => {
    queryParams.value.currentPage = newPage;
    queryParams.value.pageSize = newPageSize;
    handleQuery();
};

// 页面加载时自动查询一次
onMounted(() => {
  handleQuery();
});

</script>

<style scoped>
.el-input__inner {
  margin-left: 2px;
}
</style>